package repository

import (
	"git.huoys.com/block_chain/mall/ecode"
	pb "git.huoys.com/block_chain/mall/internal/shop/api"
	"git.huoys.com/block_chain/mall/internal/shop/model"
)

// 创建订单
func (ser *shopRepository) AddOrder(order model.Order) (id uint64, err error) {
	var goods model.Goods
	var tx = ser.db.Begin()
	defer tx.Rollback()
	// 判断商品是否下架
	err = tx.First(&goods, order.GoodsID).Error
	if err != nil {
		return 0, ecode.ErrGoodsNotFound
	}
	if !goods.IsSale || goods.Cid == 0 || goods.WalletAddr == "" {
		return 0, ecode.ErrGoodsNotFound
	}
	// 创建订单
	err = tx.Create(&order).Error
	if err != nil {
		return 0, err
	}
	// 修改订单状态
	err = tx.Model(&model.Goods{}).Where("id = ?", order.GoodsID).Update("is_sale", false).Error
	if err != nil {
		return 0, err
	}
	err = tx.Commit().Error
	return order.ID, err
}

// 修改订单
func (ser *shopRepository) SetOrder(order model.Order) (err error) {
	return ser.db.Updates(&order).Error
}

// 交易成功，修改订单状态为交易成功，并修改商品信息
func (ser *shopRepository) OrderSuccess(goodsId, orderId uint64, addr, orderHash string) (err error) {
	var tx = ser.db.Begin()
	defer tx.Rollback()
	err = tx.Model(&model.Goods{}).Where("id = ?", goodsId).Update("wallet_addr", addr).Error
	if err != nil {
		return err
	}
	err = tx.Model(&model.Order{}).Where("id = ?", orderId).Update("block_hash", orderHash).Update("status", pb.OrderStatus_OrderStatus_Success).Error
	if err != nil {
		return err
	}
	return tx.Commit().Error
}

// 查询用户订单列表 可以分类
func (ser *shopRepository) GetOrderList(uid uint64, status uint64) (orders []model.Order, err error) {
	var sql = ser.db.Model(&model.Order{}).Where("uid = ?", uid)
	if status > 0 {
		sql.Where("status = ?", status)
	}
	err = sql.Find(&orders).Error
	return orders, err
}

// 获取订单详情
func (ser *shopRepository) GetOrder(oid uint64) (orders model.Order, err error) {
	err = ser.db.First(&orders, oid).Error
	return orders, err
}
